// Copyright Epic Games, Inc. All Rights Reserved.

#include "status_cmd.h"

#include <zencore/compactbinary.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/string.h>
#include <zencore/uid.h>
#include <zenutil/zenserverprocess.h>

namespace zen {

StatusCommand::StatusCommand()
{
	m_Options.add_option("", "p", "port", "Host port", cxxopts::value(m_Port)->default_value("0"), "<hostport>");
	m_Options.add_option("", "", "data-dir", "Path to data directory to inspect for running server", cxxopts::value(m_DataDir), "<file>");
}

StatusCommand::~StatusCommand() = default;

int
StatusCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
	ZEN_UNUSED(GlobalOptions);

	if (!ParseOptions(argc, argv))
	{
		return 0;
	}

	uint16_t EffectivePort = 0;
	if (!m_DataDir.empty())
	{
		if (!std::filesystem::is_regular_file(m_DataDir / ".lock"))
		{
			ZEN_CONSOLE("lock file does not exist in directory '{}'", m_DataDir);
			return 1;
		}
		LockFileInfo Info = ReadLockFilePayload(LoadCompactBinaryObject(IoBufferBuilder::MakeFromFile(m_DataDir / ".lock")));
		std::string	 Reason;
		if (!ValidateLockFileInfo(Info, Reason))
		{
			ZEN_CONSOLE("lock file in directory '{}' is not valid. Reason: '{}'", m_DataDir, Reason);
			return 1;
		}
		EffectivePort = Info.EffectiveListenPort;
	}

	ZenServerState State;
	if (!State.InitializeReadOnly())
	{
		ZEN_CONSOLE("no Zen state found");

		return 0;
	}

	ZEN_CONSOLE("{:>5} {:>6} {:>24}", "port", "pid", "session");
	State.Snapshot([&](const ZenServerState::ZenServerEntry& Entry) {
		bool MatchesAnyPort		  = (m_Port == 0) && (EffectivePort == 0);
		bool MatchesEffectivePort = (EffectivePort != 0) && (Entry.EffectiveListenPort.load() == EffectivePort);
		bool MatchesDesiredPort	  = (m_Port != 0) && (Entry.DesiredListenPort.load() == m_Port);
		if (MatchesAnyPort || MatchesEffectivePort || MatchesDesiredPort)
		{
			StringBuilder<25> SessionStringBuilder;
			Entry.GetSessionId().ToString(SessionStringBuilder);
			ZEN_CONSOLE("{:>5} {:>6} {:>24}", Entry.EffectiveListenPort.load(), Entry.Pid.load(), SessionStringBuilder);
		}
	});

	return 0;
}

}  // namespace zen
